package com.doubao.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.result.Result;
import com.doubao.device.dto.CategoryDTO;
import com.doubao.device.dto.request.CreateCategoryRequest;
import com.doubao.device.dto.request.UpdateCategoryRequest;
import com.doubao.device.entity.DeviceCategory;
import com.doubao.device.exception.BusinessException;
import com.doubao.device.exception.DuplicateDataException;
import com.doubao.device.mapper.DeviceCategoryMapper;
import com.doubao.device.service.DeviceCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DeviceCategoryServiceImpl extends ServiceImpl<DeviceCategoryMapper, DeviceCategory> implements DeviceCategoryService {

    @Override
    public Result<CategoryDTO> createCategory(CreateCategoryRequest request) {
        // 检查编码是否重复
        LambdaQueryWrapper<DeviceCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceCategory::getCode, request.getCode());
        if (count(queryWrapper) > 0) {
            throw new DuplicateDataException("分类编码已存在");
        }
        
        DeviceCategory category = new DeviceCategory();
        BeanUtils.copyProperties(request, category);
        
        // 设置状态和时间
        category.setStatus(1);
        category.setCreatedAt(LocalDateTime.now());
        category.setUpdatedAt(LocalDateTime.now());
        
        boolean saved = save(category);
        if (!saved) {
            return Result.failed("创建分类失败");
        }
        
        CategoryDTO dto = convertToDTO(category);
        return Result.success(dto);
    }

    @Override
    @CacheEvict(value = "category", key = "#request.id")
    public Result<CategoryDTO> updateCategory(UpdateCategoryRequest request) {
        DeviceCategory category = getById(request.getId());
        if (category == null) {
            return Result.failed("分类不存在");
        }
        
        // 检查编码是否重复
        if (request.getCode() != null && !request.getCode().equals(category.getCode())) {
            LambdaQueryWrapper<DeviceCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DeviceCategory::getCode, request.getCode());
            if (count(queryWrapper) > 0) {
                throw new DuplicateDataException("分类编码已存在");
            }
        }
        
        // 更新属性
        if (request.getName() != null) {
            category.setName(request.getName());
        }
        if (request.getCode() != null) {
            category.setCode(request.getCode());
        }
        if (request.getIcon() != null) {
            category.setIcon(request.getIcon());
        }
        if (request.getSortOrder() != null) {
            category.setSortOrder(request.getSortOrder());
        }
        
        category.setUpdatedAt(LocalDateTime.now());
        
        boolean updated = updateById(category);
        if (!updated) {
            return Result.failed("更新分类失败");
        }
        
        CategoryDTO dto = convertToDTO(category);
        return Result.success(dto);
    }

    @Override
    @CacheEvict(value = "category", key = "#categoryId")
    public Result<Void> deleteCategory(Long categoryId) {
        DeviceCategory category = getById(categoryId);
        if (category == null) {
            return Result.failed("分类不存在");
        }
        
        // 检查是否有智能体使用此分类
        // 这里应该添加检查逻辑
        
        boolean removed = removeById(categoryId);
        if (!removed) {
            return Result.failed("删除分类失败");
        }
        
        return Result.success();
    }

    @Override
    @Cacheable(value = "category", key = "#categoryId", unless = "#result.data == null")
    public Result<CategoryDTO> getCategoryDetail(Long categoryId) {
        DeviceCategory category = getById(categoryId);
        if (category == null) {
            return Result.failed("分类不存在");
        }
        
        CategoryDTO dto = convertToDTO(category);
        return Result.success(dto);
    }

    @Override
    @Cacheable(value = "categories", unless = "#result.data == null")
    public Result<List<CategoryDTO>> getAllCategories() {
        LambdaQueryWrapper<DeviceCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(DeviceCategory::getSortOrder);
        
        List<DeviceCategory> categories = list(queryWrapper);
        List<CategoryDTO> dtoList = categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        return Result.success(dtoList);
    }

    @Override
    @Cacheable(value = "enabledCategories", unless = "#result.data == null")
    public Result<List<CategoryDTO>> getEnabledCategories() {
        LambdaQueryWrapper<DeviceCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceCategory::getStatus, 1)
                .orderByAsc(DeviceCategory::getSortOrder);
        
        List<DeviceCategory> categories = list(queryWrapper);
        List<CategoryDTO> dtoList = categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        return Result.success(dtoList);
    }

    @Override
    @CacheEvict(value = {"category", "categories", "enabledCategories"}, key = "#categoryId")
    public Result<Void> updateSortOrder(Long categoryId, Integer sortOrder) {
        DeviceCategory category = getById(categoryId);
        if (category == null) {
            return Result.failed("分类不存在");
        }
        
        category.setSortOrder(sortOrder);
        category.setUpdatedAt(LocalDateTime.now());
        
        boolean updated = updateById(category);
        if (!updated) {
            return Result.failed("更新分类排序失败");
        }
        
        return Result.success();
    }

    /**
     * 将实体转换为DTO
     */
    private CategoryDTO convertToDTO(DeviceCategory category) {
        CategoryDTO dto = new CategoryDTO();
        BeanUtils.copyProperties(category, dto);
        return dto;
    }

    @Override
    @CacheEvict(value = {"category", "categories", "enabledCategories"}, key = "#categoryId")
    public Result<Void> updateStatus(Long categoryId, Integer status) {
        // 检查分类是否存在
        DeviceCategory category = getById(categoryId);
        if (category == null) {
            return Result.failed("分类不存在");
        }

        // 更新状态
        category.setStatus(status);
        category.setUpdatedAt(LocalDateTime.now());

        // 保存更新
        boolean updated = updateById(category);
        if (!updated) {
            return Result.failed("更新分类状态失败");
        }

        return Result.success();
    }

} 